package org.bbelovic.devel.snake;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JFrame;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Class holding all GUI components and methods for displaying application window.
 */
public class ApplicationFrame {

    /** logger instance */
    private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationFrame.class);
    /** application window title */
    private static final String FRAME_TITLE = "The Snake game";
    /** Swing {@link JFrame} holding all components */
    private final JFrame frame = new JFrame();
    /** {@link DrawPanel} for painting game scene */
    private final DrawPanel panel;
    /** application window width */
    private final int width;
    /** application window height */
    private final int height;

    /**
     * Constructs application window
     * @param width application window width
     * @param height application window height
     * @param panel drawing panel
     */
    public ApplicationFrame(final int width, final int height, final DrawPanel panel) {
        this.width = width;
        this.height = height;
        this.panel = panel;
    }
    
    /**
     * Constructs application frame. Set all components and dimension, register listener for catching keyboard inputs.
     */
    public void createAndShowGUI() {
        frame.setTitle(FRAME_TITLE);
        frame.setResizable(false);
        frame.addKeyListener(new DrawPanelKeyAdapter());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(0, 0, this.width, this.height);
        frame.add(panel);
        frame.setVisible(true);
    }

    /**
     * Handles input from keyboard. This is important for handling change in
     * snake direction.
     */
    private class DrawPanelKeyAdapter extends KeyAdapter {
        @Override
        public void keyPressed(final KeyEvent evt) {
            switch (evt.getKeyCode()) {
                case KeyEvent.VK_LEFT:
                    LOGGER.info("Left key pressed");
                    panel.setDirection(Direction.LEFT);
                    break;
                case KeyEvent.VK_RIGHT:
                    LOGGER.info("Right key pressed");
                    panel.setDirection(Direction.RIGHT);
                    break;
                case KeyEvent.VK_UP:
                    LOGGER.info("Up key pressed");
                    panel.setDirection(Direction.UP);
                    break;
                case KeyEvent.VK_DOWN:
                    LOGGER.info("Down key pressed");
                    panel.setDirection(Direction.DOWN);
                    break;
                default:
                    System.out.println("Unknown key pressed");
            }
        }
    }
}
